// JavaScript Document
	var daysName = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
	// create database
	var db = window.openDatabase('Calendar', '0.1', 'AceCalendar', 200000);
	// create table
	db.transaction(function (tx) {
  		tx.executeSql('CREATE TABLE IF NOT EXISTS EVENTS (id integer, date NUMERIC, logTitle, log, PRIMARY KEY (id))');
	});
	// Wait for device API libraries to load
	//
	$(document).ready(onLoad);
	function onLoad() {	
		$("#dayEventList").swipe({
  			swipeLeft:function(event, direction, distance, duration, fingerCount) {
					$("body").pagecontainer("change", "index2.html", { showLoadMsg: true, transition: 'slide', role:'page'});
			},
			swipeRight:function(event, direction, distance, duration, fingerCount) {
					$("body").pagecontainer("change", "clock.html", { showLoadMsg: true, transition: 'slide', role:'page',reverse:true}); 
		}});
			
		var year = getURLQueryString("y"), month = getURLQueryString("m");
		var date;
		if(year != "")
			date = new Date(year,month,1);
		else{
				date = new Date();
				date.setDate(1);
		}
		listTheDaysOfMonth(date.getFullYear(), date.getMonth());
		listEventsOfMonth(date.getFullYear(), date.getMonth());
		
		//點擊dayWidget 新增日記
		$(".dayWidget").click(function(){
				var str = $(this).children(".dayContent").first().attr('id');
				str = str.match("[0-9]+");
				str = String.format("?y={0}&m={1}&d={2}",date.getFullYear(),date.getMonth(),str)
				window.location.href = "eventDetail.html" + str;
			})
	}
	//List all days of one Month
	function listTheDaysOfMonth(year,month){
		var date = new Date(year,month,1);				
		$("#lbDayListMonth").html(String.format("{0}.{1}",	date.getFullYear(), String.padLeft((date.getMonth()+1),2)));
		var preMonth =  new Date(year, month-1 ,1);
		$("#dayPreMonth").attr("href","?y=" + preMonth.getFullYear() + "&m=" + preMonth.getMonth());
		var nextMonth = new Date(year, month+1 ,1);
		$("#dyaNextMonth").attr("href","?y=" + nextMonth.getFullYear() + "&m=" +  nextMonth.getMonth());
		var i = 0;
		do
		{
			var dayName = daysName[date.getDay()];
			var strClassHollday = null;
			if(date.getDay() == 0 || date.getDay() ==6)
					strClassHollday = "dayHollday";
			var widget = String.format('<div class="dayWidget"><div class="dayTitle"><div class="dayNumber {0}">{1}</div><div style="font-family: "customfont";" class="dayWeek {0}">{2}</div><a data-ajax="false" href="eventDetail.html"><img src="img/add.png"></a></div><div id="widget-Events{3}" class="dayContent"></div></div><!-- /dayWidget -->',
		strClassHollday, date.getDate(),dayName,date.getDate());

			$("#dateContent").append(widget);
			date.setDate(date.getDate()+1);
		} while(month == date.getMonth());
	}
	
	//List the Events of the Month
	function listEventsOfMonth(year,month)
	{
		//查詢字串設定：2014-07-01
		var date = new Date(year,month,1);
		var strStart = String.format("{0}-{1}-01", date.getFullYear(), String.padLeft((date.getMonth()+1),2));
		var nextMonth = new Date(year, month+1 ,1)
		var strEnd = String.format("{0}-{1}-01", nextMonth.getFullYear(), String.padLeft((nextMonth.getMonth()+1),2));
		
		var ltEvents = [];
		db.transaction( function(tx) {
			//SELECT * FROM EVENTS WHERE date(date) >= date("2014-07-01") and date(date) < date("2014-08-01")
			tx.executeSql('SELECT * FROM EVENTS WHERE date(date) >= date(?) and date(date) < date(?)',
			[strStart,strEnd], function(tx,results) {
					for	(i=0;i<results.rows.length;i++)
					{
						var row = results.rows.item(i);
						m_date = new Date(row['date']);
						if(!ltEvents[m_date.getDate()])
								ltEvents[m_date.getDate()]=[];
						ltEvents[m_date.getDate()].push({ 'id' : row['id'], 'date' :new Date(row['date']),
									  'logTitle' : row['logTitle'], 'log' : row['log']});
					}
				});
		},
		//error callback
		function() {}, 
		//success callback
		function() {
				showEventLogs(ltEvents);
			});
	}
	//showEventLogs in Widget
	function showEventLogs(eventsList){
		i=1;
		while(i < eventsList.length){
			if(eventsList[i]){
				//<ul><li>09:30 上午開會</li></ul>
				var strhtml = "<ul>";
				for(var j=0; j < 4 ; j++){
					if(eventsList[i][j]){
						m_date = eventsList[i][j].date;
						strhtml += String.format('<li><a data-ajax="false" style="color:black;" href="eventDetail.html?id={3}">{0}:{1} {2}</a></li>',
						 String.padLeft(m_date.getHours(),2),String.padLeft( m_date.getMinutes(),2),
						 eventsList[i][j].logTitle, eventsList[i][j].id);
					}else{
						strhtml += ""
					}
				}
				strhtml += "</ul>";
				//alert(strhtml);
				$("#widget-Events" + eventsList[i][0].date.getDate()).html(strhtml);
			}
			i++;
		}	
	}